import { SearchCase, SearchTemplate, SearchNews, SearchWorks } from "@/api";

export const useContent = () => {
    const route = useRoute();
    const keyword = ref(route.query.keyword || "");
    const searchKeyword = ref(route.query.keyword || "");
    const tabActive = ref(0);
    const isLoading = ref(false);
    const pagination = reactive({
        size: 40,
        page: 1,
    });
    const tabs = reactive([
        {
            label: "案例",
            value: "Case",
            data: [],
            api: SearchCase,
        },
        {
            label: "模板库",
            value: "Template",
            data: [],
            api: SearchTemplate,
        },
        {
            label: "作品广场",
            value: "Works",
            data: [],
            api: SearchWorks,
        },
        {
            label: "新闻动态",
            value: "News",
            data: [],
            api: SearchNews,
        },
    ]);

    const getList = async () => {
        const Item = tabs[tabActive.value];
        isLoading.value = true;
        const res = await Item.api({
            keyword: searchKeyword.value,
        });
        isLoading.value = false;
        if (res.code == 200) {
            Item.data = res.data;
        }
    };

    const onSearch = async () => {
        searchKeyword.value = keyword.value;
        pagination.page = 1;
        //获取数据
        getList();
    };

    const onTabClick = (index) => {
        tabActive.value = index;
        pagination.page = 1;
        getList();
    };

    const getData = (data) => {
        return data.slice(
            (pagination.page - 1) * pagination.size,
            pagination.page * pagination.size
        );
    };

    const pageChangeHandle = (page) => {
        pagination.page = page;
        window.scrollTo({
            top: 0,
            left: 0,
            behavior: "smooth",
        });
    };

    return {
        pagination,
        tabActive,
        tabs,
        keyword,
        isLoading,
        onSearch,
        onTabClick,
        getList,
        getData,
        pageChangeHandle,
    };
};
